package com.dat255.tentatime;



import java.text.ParseException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.dat255.tentatime.es.ExternalStorage;
/**
 * This class will display a current exam and allow the user to
 * change the data and save it
 * @author Joseph
 *
 */
public class ChangeExamActivity extends Activity {
	
	private EditText courseid, coursename, courseplace;
	private DatePicker datepicker;
	private TimePicker timepicker;
	private Button buttonSave, buttonCancel;
	private Exam oldExam;
	//Dialog ID
	private static final int DIALOG_ID = 47;
	private boolean sucess = false;
	private String date,time;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exam_form);
		
        
		 
        this.attachGUIcomponents();
        this.setExamtoForm();
        
        buttonSave.setOnClickListener(saveListener);
        buttonCancel.setOnClickListener(cancelListener);
        
       
        
      
       
        
	}
	 /**
     * The internal method will "connect" the input/output components
     * of the GUI for this activity for use in this code
     */
    private void attachGUIcomponents(){
    	

		 //Assign components
       courseid = (EditText) findViewById(R.id.formCourseID);
       coursename = (EditText) findViewById(R.id.formCourseName);
       courseplace = (EditText) findViewById(R.id.formPlace);
       
       datepicker = (DatePicker) findViewById(R.id.datePicker);
       timepicker = (TimePicker) findViewById(R.id.timePicker);
       
       buttonSave = (Button) findViewById(R.id.buttonSave);
       buttonCancel = (Button) findViewById(R.id.buttonCancel);
       
    	
    	
    }
    
    /**
     * This internal method will validate the input entred on the form
     * and assist the user to correct the mistakes
     * @return true if every input parameter on the form is correct
     */
    private boolean validateInput(){
    	
    		boolean procced = true;
    	   
		   if(!InputUtility.validateCourseID(courseid.getText().toString().trim())){
			   
			   
			   
			   Toast.makeText(ChangeExamActivity.this," Not a valid courseid! Please review the entred data!", Toast.LENGTH_LONG).show();
			   procced = false;
			   
		   }else if (!InputUtility.validateName(coursename.getText().toString().trim())){
				
			   Toast.makeText(ChangeExamActivity.this," Not a valid coursename!", Toast.LENGTH_LONG).show();
			   procced = false;

			}else if(!InputUtility.validateName(courseplace.getText().toString().trim())){
				
				Toast.makeText(ChangeExamActivity.this," Not a valid name for place! Please review the entred data!", Toast.LENGTH_LONG).show();
 			   procced = false;
				
				
			}else if(!InputUtility.validateTime(time)){
				
				Toast.makeText(ChangeExamActivity.this," Not a valid time! Please review the entred data!", Toast.LENGTH_LONG).show();
 			   procced = false;
				
			} else
				try {
					if(!InputUtility.validateDate(date)){
						
						Toast.makeText(ChangeExamActivity.this," Old dates and todays are not valid! Please review the entred data!", Toast.LENGTH_LONG).show();
	        			   procced = false;
						
					}else{
						
						procced = true;
						
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    	
    	
		   		return procced;
    	
    }
    /**
     * This internal method will display the current details on the exam
     */
    private void setExamtoForm(){
    	
  //Setvalues to the input form
        
        Bundle data = getIntent().getExtras();
        
        oldExam = data.getParcelable("changeexam");
        //Set values to the input
        courseid.setText(oldExam.getCourseID().trim());
        courseid.setEnabled(false);
        coursename.setText(oldExam.getCourseName().trim());
        courseplace.setText(oldExam.getPlace().trim());
     
    	
    }


	//Create an anonymous implementation of OnClickListener
    private OnClickListener saveListener = new OnClickListener() {
        
    	
    	public void onClick(View v) {
       
    		AlertDialog.Builder builder = new AlertDialog.Builder(ChangeExamActivity.this);
	        	
				builder.setMessage("Do you want to save the exam?")
				       .setCancelable(false)
				       .setTitle("Confirmation")
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	  
				        	   if(InputUtility.connectedToTheInternet(ChangeExamActivity.this)){
				        		   
				        		   time = timepicker.getCurrentHour().toString() + ":" + timepicker.getCurrentMinute();
				                  	// jan starts at 0
				                  	date = datepicker.getDayOfMonth() + "/" + (datepicker.getMonth()+1) + "/" + datepicker.getYear();
				                  	
				                  	
				                  	if(validateInput()){
				                  	showDialog(DIALOG_ID);
						        	new ChangeExam().execute();
				                  	}
					        	   
				        	   }else{
					        		   
					        		   Toast.makeText(ChangeExamActivity.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
					        	   }
				        	
				
								
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				
				AlertDialog alert = builder.create();
						alert.show();
	        } 
    	

    };
     
    // Create an anonymous implementation of OnClickListener
    private OnClickListener cancelListener = new OnClickListener() {
        public void onClick(View v) {
	AlertDialog.Builder builder = new AlertDialog.Builder(ChangeExamActivity.this);
        	
			builder.setMessage("Do you want to cancel")
			       .setCancelable(false)
			       .setTitle("Confirmation")
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	  
			        	   Intent intent = new Intent(); 
			                intent.setClass(getApplicationContext(), FindActivity.class);
			                startActivity(intent);
			                finish();
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			
			AlertDialog alert = builder.create();
					alert.show();
        } 
      
    };
    
    /**
	 * Creates a progressdialog, that is displayed  when the user makes a search	
	 */
	  @Override
	  protected Dialog onCreateDialog(int id) {
	   
		  switch (id) {
	    case DIALOG_ID: {
	    	
	      ProgressDialog dialog = new ProgressDialog(this);
	      
	      dialog.setMessage(ChangeExamActivity.this.getString(R.string.dialogmsg));
	      
	      dialog.setIndeterminate(true);
	      
	      dialog.setCancelable(true);
	      
	      return dialog;
	    }
	    
		  }

	    return null;
	  }
	  
	  @Override
		protected void onResume() {
		  UserState app = ((UserState)ChangeExamActivity.this.getApplication());
			super.onResume();
			
			if(!app.getState()){
				Toast.makeText(this, "Form removed due to inactivity", Toast.LENGTH_LONG).show();
				
				finish();
				
			}
			
		}
    /*****************************************************/
   	/************** ASYNCTASKS      **********************/
   	/*****************************************************/
   			
   		
   	/**
   	 * This internal class, will help us create an asynctask when we search for an exam
   	 * in the server database, instead of burden the UI thread	
   	 * @author Joseph
   	 *
   	 */
   	private class ChangeExam extends AsyncTask<Void,Integer,String>{

   		
   		/**
   		 * This method will try to submit an exam to the sercer
   		 */
   		@Override
   		protected String doInBackground(Void... arg0) {
   			String msg =""; 
   			
   			
   			try {
   				ExternalStorage.edit(coursename.getText().toString().trim(),
   						courseid.getText().toString().trim(), date, time, 
   						courseplace.getText().toString().trim());
   				//ExternalStorage.remove(oldExam.getCourseID());
   				msg = "The exam was succesfully changed on the server";
   				sucess = true;
   			} catch (Exception e) {
   				msg = "Error!! The exam was not stored on the server";
   			}
   			
   			return msg;
   		}
   		@Override
   		protected void onProgressUpdate(Integer... values) {
   			// TODO Auto-generated method stub
   			super.onProgressUpdate(values);
   		}
   		/**
   		 * This method is executed after doInBackground and will present the result 
   		 * from doInBackground
   		 */
   		@Override
   		protected void onPostExecute(String result) {
   			
   			super.onPostExecute(result);
   			//Disable dialog box
   			dismissDialog(DIALOG_ID);
   			
   			Toast.makeText(ChangeExamActivity.this, result, Toast.LENGTH_LONG).show();
   			
   			//If submit was succesfull move to next activity
   			if(sucess){
   				
   			
   				Intent intent = new Intent(ChangeExamActivity.this, FindActivity.class);
   				ChangeExamActivity.this.startActivity(intent); 
   				finish();
   					
   	    };
   	    
   			
   			
   		}
   		

   	}


}
